<?php
require_once '../config.php';
require_once 'BaseAPI.php';

handleCORS();

class CategoriesAPI extends BaseAPI {
    
    public function handleRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        
        // 优先从GET/POST参数获取action，兼容虚拟主机
        $action = $_GET['action'] ?? $_POST['action'] ?? '';
        $id = $_GET['id'] ?? $_POST['id'] ?? '';
        
        // 如果没有action参数，尝试从URL路径解析
        if (empty($action)) {
            $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
            $pathParts = explode('/', trim($path, '/'));
            $action = end($pathParts);
            
            // 移除.php后缀
            $action = str_replace('.php', '', $action);
            
            // 检查是否是数字ID
            if (is_numeric($action)) {
                $id = $action;
                $action = 'category'; // 默认操作
            }
        }
        
        try {
            switch ($method) {
                case 'GET':
                    if ($id || is_numeric($action)) {
                        $categoryId = $id ?: $action;
                        $this->getCategory($categoryId);
                    } else {
                        $this->getCategories();
                    }
                    break;
                case 'POST':
                    if ($action === 'update') {
                        // 支持POST方式的更新（虚拟主机兼容）
                        if ($action === 'update') {
                            if ($id) {
                                $this->updateCategory($id);
                            } else {
                                sendErrorResponse('缺少分组ID', 400);
                            }
                        }
                    } elseif ($action === 'reorder') {
                        $this->reorderCategories();
                    } else {
                        $this->createCategory();
                    }
                    break;
                case 'PUT':
                    if ($id || is_numeric($action)) {
                        $categoryId = $id ?: $action;
                        $this->updateCategory($categoryId);
                    } else {
                        sendErrorResponse('缺少分组ID', 400);
                    }
                    break;
                default:
                    sendErrorResponse('不支持的请求方法', 405);
            }
        } catch (Exception $e) {
            logActivity("分组API错误: " . $e->getMessage(), 'ERROR');
            sendErrorResponse('服务器内部错误', 500);
        }
    }
    
    private function getCategories() {
        $user = $this->requireAuth();
        
        // 获取用户的所有分组
        $sql = "
            SELECT c.*, 
                   COUNT(b.id) as bookmark_count
            FROM categories c 
            LEFT JOIN bookmarks b ON c.id = b.category_id AND b.user_id = c.user_id
            WHERE c.user_id = ? 
            GROUP BY c.id
            ORDER BY c.sort_order ASC, c.created_at ASC
        ";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$user['id']]);
        $categories = $stmt->fetchAll();
        
        sendSuccessResponse(['categories' => $categories]);
    }
    
    private function getCategory($id) {
        $user = $this->requireAuth();
        
        $stmt = $this->db->prepare("
            SELECT c.*, COUNT(b.id) as bookmark_count
            FROM categories c 
            LEFT JOIN bookmarks b ON c.id = b.category_id AND b.user_id = c.user_id
            WHERE c.id = ? AND c.user_id = ?
            GROUP BY c.id
        ");
        $stmt->execute([$id, $user['id']]);
        $category = $stmt->fetch();
        
        if (!$category) {
            sendErrorResponse('分组不存在', 404);
        }
        
        sendSuccessResponse(['category' => $category]);
    }
    
    private function createCategory() {
        $user = $this->requireAuth();
        $data = getRequestData();
        
        // 验证输入
        $rules = [
            'name' => [
                'required' => true,
                'max_length' => 100,
                'message' => '分组名称不能为空且不超过100个字符'
            ],
            'description' => [
                'max_length' => 1000,
                'message' => '描述不能超过1000个字符'
            ],
            'color' => [
                'pattern' => '/^#[0-9A-Fa-f]{6}$/',
                'message' => '颜色格式不正确'
            ],
            'icon' => [
                'max_length' => 50,
                'message' => '图标类名不能超过50个字符'
            ]
        ];
        
        $errors = validateInput($data, $rules);
        if (!empty($errors)) {
            sendErrorResponse('输入验证失败', 422, ['errors' => $errors]);
        }
        
        $name = $data['name'];
        $description = $data['description'] ?? '';
        $color = $data['color'] ?? '#667eea';
        $icon = $data['icon'] ?? 'fas fa-folder';
        
        // 检查分组名称是否已存在
        $stmt = $this->db->prepare("SELECT id FROM categories WHERE user_id = ? AND name = ?");
        $stmt->execute([$user['id'], $name]);
        if ($stmt->fetch()) {
            sendErrorResponse('分组名称已存在');
        }
        
        // 获取下一个排序序号
        $stmt = $this->db->prepare("SELECT COALESCE(MAX(sort_order), -1) + 1 as next_order FROM categories WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        $sortOrder = $stmt->fetch()['next_order'];
        
        // 创建分组
        $stmt = $this->db->prepare("
            INSERT INTO categories (user_id, name, description, color, icon, sort_order) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        if ($stmt->execute([$user['id'], $name, $description, $color, $icon, $sortOrder])) {
            $categoryId = $this->db->lastInsertId();
            
            // 获取创建的分组
            $stmt = $this->db->prepare("
                SELECT c.*, COUNT(b.id) as bookmark_count
                FROM categories c 
                LEFT JOIN bookmarks b ON c.id = b.category_id AND b.user_id = c.user_id
                WHERE c.id = ?
                GROUP BY c.id
            ");
            $stmt->execute([$categoryId]);
            $category = $stmt->fetch();
            
            logActivity("用户创建分组: {$user['username']} - $name");
            sendSuccessResponse(['category' => $category], '分组创建成功');
        } else {
            sendErrorResponse('分组创建失败');
        }
    }
    
    private function updateCategory($id) {
        $user = $this->requireAuth();
        $data = getRequestData();
        
        // 验证分组是否存在且属于当前用户
        $stmt = $this->db->prepare("SELECT * FROM categories WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $user['id']]);
        $category = $stmt->fetch();
        
        if (!$category) {
            sendErrorResponse('分组不存在', 404);
        }
        
        // 验证输入
        $rules = [
            'name' => [
                'max_length' => 100,
                'message' => '分组名称不能超过100个字符'
            ],
            'description' => [
                'max_length' => 1000,
                'message' => '描述不能超过1000个字符'
            ],
            'color' => [
                'pattern' => '/^#[0-9A-Fa-f]{6}$/',
                'message' => '颜色格式不正确'
            ],
            'icon' => [
                'max_length' => 50,
                'message' => '图标类名不能超过50个字符'
            ]
        ];
        
        $errors = validateInput($data, $rules);
        if (!empty($errors)) {
            sendErrorResponse('输入验证失败', 422, ['errors' => $errors]);
        }
        
        $updates = [];
        $params = [];
        
        if (isset($data['name']) && $data['name'] !== $category['name']) {
            // 检查新名称是否已存在
            $stmt = $this->db->prepare("SELECT id FROM categories WHERE user_id = ? AND name = ? AND id != ?");
            $stmt->execute([$user['id'], $data['name'], $id]);
            if ($stmt->fetch()) {
                sendErrorResponse('分组名称已存在');
            }
            $updates[] = 'name = ?';
            $params[] = $data['name'];
        }
        
        if (isset($data['description'])) {
            $updates[] = 'description = ?';
            $params[] = $data['description'];
        }
        
        if (isset($data['color'])) {
            $updates[] = 'color = ?';
            $params[] = $data['color'];
        }
        
        if (isset($data['icon'])) {
            $updates[] = 'icon = ?';
            $params[] = $data['icon'];
        }
        
        if (isset($data['sort_order']) && is_numeric($data['sort_order'])) {
            $updates[] = 'sort_order = ?';
            $params[] = intval($data['sort_order']);
        }
        
        if (empty($updates)) {
            sendErrorResponse('没有需要更新的信息');
        }
        
        $params[] = $id;
        $sql = "UPDATE categories SET " . implode(', ', $updates) . " WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        
        if ($stmt->execute($params)) {
            // 获取更新后的分组
            $stmt = $this->db->prepare("
                SELECT c.*, COUNT(b.id) as bookmark_count
                FROM categories c 
                LEFT JOIN bookmarks b ON c.id = b.category_id AND b.user_id = c.user_id
                WHERE c.id = ?
                GROUP BY c.id
            ");
            $stmt->execute([$id]);
            $updatedCategory = $stmt->fetch();
            
            logActivity("用户更新分组: {$user['username']} - {$updatedCategory['name']}");
            sendSuccessResponse(['category' => $updatedCategory], '分组更新成功');
        } else {
            sendErrorResponse('分组更新失败');
        }
    }
    
    
    private function reorderCategories() {
        $user = $this->requireAuth();
        $data = getRequestData();
        
        if (!isset($data['categories']) || !is_array($data['categories'])) {
            sendErrorResponse('缺少分组排序数据', 400);
        }
        
        try {
            $this->db->beginTransaction();
            
            foreach ($data['categories'] as $index => $categoryData) {
                if (!isset($categoryData['id'])) {
                    continue;
                }
                
                $stmt = $this->db->prepare("
                    UPDATE categories 
                    SET sort_order = ? 
                    WHERE id = ? AND user_id = ?
                ");
                $stmt->execute([$index, $categoryData['id'], $user['id']]);
            }
            
            $this->db->commit();
            
            logActivity("用户重新排序分组: {$user['username']}");
            sendSuccessResponse(null, '分组排序更新成功');
            
        } catch (Exception $e) {
            $this->db->rollBack();
            sendErrorResponse('分组排序更新失败');
        }
    }
    
    // getAuthToken() 和 requireAuth() 已在 BaseAPI 中实现
}

// 处理请求
$api = new CategoriesAPI();
$api->handleRequest();
?>
